//
//  QXStatusCell.swift
//  QXWeibo
//
//  Created by QinXin on 15/6/30.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage

protocol QXStatusCellDelegate: NSObjectProtocol {
    func statusCellDidSelectPic(cell:QXStatusCell, idx: Int)
}

class QXStatusCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
    
    var picViewWidthCons: NSLayoutConstraint?
    var picViewHeightCons: NSLayoutConstraint?
    var picViewTopCons: NSLayoutConstraint?
          
    // 懒加载子空间
    lazy var topLineView = UIView()
    lazy var iconView = UIImageView()
    lazy var nameLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
    lazy var memberIconView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
    lazy var vipIconView: UIImageView = UIImageView(image: UIImage(named: "avatar_grassroot"))
    lazy var timeLabel = UILabel(color: UIColor.orangeColor(), fontSize: 10)
    lazy var sourceLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
    lazy var contentLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15, mutiLines: true)
    lazy var picLayerFlow = UICollectionViewFlowLayout()
    lazy var picView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.picLayerFlow)
    lazy var footerView: QXStatusCellFooterView = QXStatusCellFooterView()
    
    weak var picDelegate: QXStatusCellDelegate?

    // 转发微博模型（这个模型为子类准备）
    var forwardLabel: UILabel?
    
    // 数据更新
    var status: QXStatus? {
        didSet {
            forwardLabel?.text = (status?.retweeted_status?.user?.name ?? "") + ": " + (status?.retweeted_status?.text ?? "")
            
            nameLabel.text = status?.user?.name
            timeLabel.text = "刚刚"
            sourceLabel.text = "来自 北方的狼"
            contentLabel.text = status?.text
            iconView.sd_setImageWithURL(status?.user!.profileURL)
            vipIconView.image = status?.user?.verifiedImage
            memberIconView.image = status?.user?.mbImage
            
            let res = getPicViewSize(status!)
            
            picViewTopCons?.constant = res.viewSize.height == 0 ? 0 : 12
            picViewWidthCons?.constant = res.viewSize.width
            picViewHeightCons?.constant = res.viewSize.height
            picLayerFlow.itemSize = res.itemSize
            
            picView.reloadData()
        }
    }
    
    // 根据配图的数量确定配图框的大小及每张配图的大小
    private func getPicViewSize(status: QXStatus) -> (viewSize: CGSize, itemSize: CGSize) {
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        let count = status.allImageURLs?.count ?? 0
        
        switch count {
        case 0:
            return (CGSizeZero, itemSize)
        case 1:
            // 当只有一张图片的时候，从缓存中取大小（采用图片完整地址的方式索引缓存的图片）
            let key = status.allImageURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            return (image.size, image.size)
        case 2:
            return (CGSize(width: itemSize.width * 2 + margin, height: itemSize.height), itemSize)
        case 3:
            return (CGSize(width: itemSize.width * 3 + margin * 2, height: itemSize.height), itemSize)
        case 4:
            return (CGSize(width: itemSize.width * 2 + margin, height: itemSize.height * 2 + margin), itemSize)
        case 5,6:
            return (CGSize(width: itemSize.width * 3 + margin * 2, height: itemSize.height * 2 + margin), itemSize)
        case 7,8,9:
            return (CGSize(width: itemSize.width * 3 + margin * 2, height: itemSize.height * 3 + margin * 2), itemSize)
        default:
            // 新浪微博一次最多只能发9张图片
            print("图片超过9张！")
            return (CGSizeZero, CGSizeZero)
        }
        
    }
    
    /// 为 tableView 返回行高
    func rowHeight(status: QXStatus) -> CGFloat {
        self.status = status
        layoutIfNeeded()
        return CGRectGetMaxY(footerView.frame)
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        addSubview(topLineView)
        addSubview(iconView)
        addSubview(nameLabel)
        addSubview(memberIconView)
        addSubview(vipIconView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        addSubview(picView)
        addSubview(footerView)
        
        contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 12
        
        topLineView.backgroundColor = UIColor(white: 0.6, alpha: 1.0)
        footerView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        picView.backgroundColor = UIColor.whiteColor()
        
        // 图框集合视图的设置
        picView.dataSource = self
        picView.delegate = self
        picView.registerClass(QXWebImageCollectionViewCell.self, forCellWithReuseIdentifier: "QXWebImageCollectionViewCell")
        picLayerFlow.minimumInteritemSpacing = 10.0
        picLayerFlow.minimumLineSpacing = 10.0
        
        // 约束
        topLineView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: UIScreen.mainScreen().bounds.size.width, height: 10), offset: CGPointZero)
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 34, height: 34), offset: CGPoint(x: 12, y: 22))
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.TopRight, referView: nameLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8))
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))
        
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: picView, size: CGSize(width: UIScreen.mainScreen().bounds.size.width, height: 44), offset: CGPoint(x: -12, y: 12))
        
    }
    
    // 这个防止使用 SB/XIB
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.allImageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("QXWebImageCollectionViewCell", forIndexPath: indexPath) as! QXWebImageCollectionViewCell
        cell.imageURL = status!.allImageURLs![indexPath.item]
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 加载对应的大图
        let url = status!.allLargeImageURLs![indexPath.item]
        let cell = picView.cellForItemAtIndexPath(indexPath) as! QXWebImageCollectionViewCell
        SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: { (bytes, total) -> Void in
            
            let progress = CGFloat(bytes) / CGFloat(total)
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                cell.imageView.progress = progress
            })
            
            }) { [unowned self] (img, error, _, _, _) -> Void in

                if error != nil {
                    print(error)
                }
                
                // 大图加载完成后通知代理打开界面
                self.picDelegate?.statusCellDidSelectPic(self, idx: indexPath.row)
                
        }
        
    }
    
}


///  用于显示单张网络图片的 collectionViewCell
class QXWebImageCollectionViewCell: UICollectionViewCell {
    var imageURL: NSURL? {
        didSet {
            imageView.sd_setImageWithURL(imageURL)
            gifImageView.hidden = !(imageURL!.absoluteString.pathExtension.lowercaseString == "gif")
        }
    }
    
    lazy var imageView: QXImageView = QXImageView()
    lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 图片进行原始比例拉伸
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        self.clipsToBounds = true
        
        addSubview(imageView)
        addSubview(gifImageView)
        // 填充到整个cell
        imageView.ff_Fill(self)
        gifImageView.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil, offset: CGPoint(x: -3, y: -3))
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


/// 页脚的视图
class QXStatusCellFooterView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(forwardBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        // 布局（水平平铺）
        ff_HorizontalTile([forwardBtn, commentBtn, likeBtn], insets: UIEdgeInsetsZero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var forwardBtn: UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", fontSize: 12)
    lazy var commentBtn: UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", fontSize: 12)
    lazy var likeBtn: UIButton = UIButton(title: "点赞", imageName: "timeline_icon_unlike", fontSize: 12)

}



